package service

import (
	"grs-report-admin/model"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func SqlPreview(ctx *gin.Context) {
	sql := ctx.Query("sql")
	log.Println(sql)
	rows, err := model.DB.Query(sql)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "查询失败",
			Result:  err.Error(),
		})
		return
	}
	columns, err := rows.Columns()
	if err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "查询失败",
			Result:  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, model.Result{
		Message: "查询成功",
		Result:  columns,
	})
}
func SqlQuery(ctx *gin.Context) {
	// 查询sql
	sql := ctx.Query("sql")
	log.Println(sql)
	rows, err := model.DB.Queryx(sql)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "查询失败",
			Result:  err.Error(),
		})
		return
	}
	sqlResult := []map[string]string{}
	columns, _ := rows.Columns()
	for rows.Next() {
		aReuslt := make(map[string]interface{})
		parseResult := make(map[string]string)
		rows.MapScan(aReuslt)
		for _, s := range columns {
			switch aReuslt[s].(type) {
			case []uint8:
				parseResult[s] = string(aReuslt[s].([]byte))
			}
		}
		sqlResult = append(sqlResult, parseResult)
	}
	if err != nil {
		ctx.JSON(http.StatusBadRequest, model.Result{
			Message: "查询失败",
			Result:  err.Error(),
		})
		return
	}
	log.Println(rows.Scan())
	ctx.JSON(http.StatusOK, model.Result{
		Message: "查询成功",
		Result:  sqlResult,
	})
}
